import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { getToken } from '_utils'
import store from '../store'
import router from '../router'
// 统一定义 所有请求默认配置
const request = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 6000
})
let loading = null
request.interceptors.request.use(function (config) {
  // 请求添加token
  if (getToken()) {
    config.headers.access_token = getToken()
  }
  // 显示loading
  loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return config
}, function (error) {
  loading.close()
  return Promise.reject(error)
})

request.interceptors.response.use(function (res) {
  const errCode = [401, 403]
  if (errCode.includes(res.data.code)) {
    // 401过期 403 没有传token
    /*
      弹出错误提示
      清除登录相关缓存
      去登录
    */
    store.commit('user/RM_USER_INFO')
    Message({
      type: 'error',
      message: '登录状态过期，或者没有登录',
      duration: 1000,
      onClose: () => {
        router.push('/login')
      }
    })
  }
  loading.close()
  return res
}, function (error) {
  loading.close()
  return Promise.reject(error)
})

export default request
